﻿namespace Text2Rss.Web.Services
{
	#region Using Directives

	using System;
	using System.IO;
	using NHibernate;
	using Text2Rss.Web.Models;
	
	#endregion

	/// <summary>
	/// Performs general operations with files
	/// </summary>
	public class FileStorage : BaseService, IFileStorage
	{
		#region Fields

		private string basePath;
		
		#endregion

		#region Constructor

		/// <summary>
		/// .ctor
		/// </summary>
		/// <param name="session">Current session</param>
		/// <param name="session">Path of the storage</param>
		public FileStorage(ISession session, string basePath)
			: base(session)
		{
			this.basePath = basePath;
		}

		#endregion // Constructor

		#region Methods

		/// <summary>
		/// Opens file stream
		/// </summary>
		/// <param name="file"></param>
		/// <returns></returns>
		public Stream OpenFile(SourceFile file)
		{
			// TODO: Add Requires class
			if (file == null)
			{
				throw new ArgumentException("The file is empty");
			}

			string fileName = GetContentFileName(file);

			if (!File.Exists(fileName))
			{
				throw new FileNotFoundException("Can't find file by name: ", fileName);
			}

			return new FileStream(fileName, FileMode.Open, FileAccess.Read);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="file"></param>
		/// <param name="stream"></param>
		public void SaveFile(SourceFile file, Stream stream)
		{
			// TODO: Add Requires class
			if (file == null)
			{
				throw new ArgumentException("The file is empty");
			}

			string fileName = GetContentFileName(file);

		}

		private string GetContentFileName(SourceFile file)
		{
			string fileName = Path.Combine(
				basePath,
				string.Format(
					"{0}\\content",
					file.Id.ToString("000000")));

			return fileName;
		}
		
		#endregion
	}
}